package jcer.core;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class TaskHandler extends BaseEventHandler {
	TaskHandler(EventDriver driver) {
		super(driver);
	}

	protected ExecutorService executor;
	public static Map<Integer, Class<?>> taskMap = new HashMap<Integer, Class<?>>();

	@Override
	public void init() {
		executor = Executors.newFixedThreadPool(driver.workNum);
	}

	@Override
	public void execute(Event event) throws Exception {
		Connection conn = event.conn;
		Packet packet = conn.packet;

		List<Task> tasks = getSubTasks(conn, packet);
		if (tasks.size() == 0) {
			throw new Exception("Empty Tasks");
		}
		conn.resultNum = tasks.size();
		conn.resultList.clear();// clear result
		for (Task task : tasks) {
			executor.execute(task);
		}
	}

	public List<Task> getSubTasks(Connection conn, Packet packet)
			throws Exception {
		List<Task> tasks = new ArrayList<Task>();
		for (Packet.TaskPacket taskPacket : packet.taskPackets) {
			if (taskMap.containsKey(taskPacket.taskId)) {
				Task task = (Task) taskMap.get(taskPacket.taskId).newInstance();
				task.taskId = taskPacket.taskId;
				task.taskNum = taskPacket.taskNum;
				task.conn = conn;
				taskPacket.buf.position(0);
				task.decode(taskPacket.buf);
				tasks.add(task);
			}
		}
		return tasks;
	}

}
